以下分享一個能接收JSON和回傳JSON的API功能範例和說明
@RequestMapping註解屬性說明
value:指定HTTP請求路徑對應到Controller中的方法 (例如:/ApiNotifications)
method:指定HTTP請求所使用的方法 (例如:POST)
consumes:指定HTTP請求提交的内容類型(Content-Type)(例如:application/json)
@RequestMapping(value = "/ApiNotifications", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<JSONObject> ApiNotifications(@RequestBody JSONObject data) throws Exception {
log.info("[ApiNotifications] : start ");
String empId = data.getString("empId");
String empName = data.getString("empName");
log.info("[ApiNotifications] : empId " +empId);
log.info("[ApiNotifications] : empName " +empName);
JSONObject result = new JSONObject();
EmpDetail empDetail = new EmpDetail(); // EmpDetail 類別
try{
empDetail.setEmpId(empId);
if(empDetailMapper.getEmpNameByEmpId(empId) == null){
empDetailMapper.insert(empDetail);
//traceLogMapper.insert("HRIS",empId,"新增員工通知");
}
}catch(Exception e){
result.put("code", "E");
result.put("msg", "錯誤");
return ResponseEntity.badRequest().body(result);
}
result.put("code", "S");
result.put("msg", "成功");
log.info("[ApiNotifications] : end ");
return ResponseEntity.ok().body(result);
}
除了API本身,Controller還能視需要搭配@Slf4j @RestController 等註解,並使用@Autowired註解自動注入容器中可以匹配的Bean
@Autowired
private EmpDetailMapper empDetailMapper;
EmpDetail類別,需要載入lombok.Data
@Data
public class EmpDetail implements Serializable {
private static final long serialVersionUID = 1L;
private String empId;
private String empName;
private List<EmpData> empData;
}
MyBatis實作,需要載入ibatis.annotations
@Mapper
public interface EmpDetailMapper {
@Select("SELECT TOP 1 empName FROM EMPDETAIL "
+ "WHERE empId = #{empId} "
)
public String getEmpNameByEmpId(@Param("empId") String empId);
@Insert("INSERT into EMPDETAIL (EMPID,EMPNAME) values "
+ "(#{empId}, #{empName})")
public void insert(EmpDetail EMPDETAIL);
}